package com.ocom.payconfig.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.MapKey;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.access.EntityMjAreaInfo;
import com.ocom.common.entity.card.EntityXfRecordWaitpay;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.entity.payconfig.EntityXfTimeZone;
import com.ocom.common.entity.payconfig.EntityXfZoneDate;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.request.srvpaccess.FindMachDto;
import com.ocom.common.request.srvpaccess.FindMachVo;
import com.ocom.common.request.srvpaccess.UpdateMachByAlarmRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.payconfig.client.AccessService;
import com.ocom.payconfig.client.CompanyClientService;
import com.ocom.payconfig.client.HumanClientService;
import com.ocom.payconfig.client.MqSimpleFeign;
import com.ocom.payconfig.service.XfTimeZoneService;
import com.ocom.payconfig.service.XfZoneDateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class MjAlarmSendController {

    @Autowired
    private AccessService accessService;

    @Autowired
    private HumanClientService humanClientService;
    @Autowired
    private MqSimpleFeign mqSimpleFeign;
    @Autowired
    private CompanyClientService companyClientService;

    @PostMapping(PayConfigUrl.Url_MjAlarmSend)
    public Result mjAlarmSend(@RequestParam Long comId) {
        try {
            FindMachVo findMachVo = new FindMachVo();
            findMachVo.setComId(comId);
            findMachVo.setIfAlarm(1);
            findMachVo.setPage(1);
            findMachVo.setSize(1000);
            Result findMach2 = accessService.FindMach2(findMachVo);
            if (200 == findMach2.getCode()) {
                Date now = new Date();
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(findMach2.getData()));
                if(jsonObject ==null || jsonObject.get("list") == null ){
                    return ResultUtil.success();
                }
                List<FindMachDto> findMachDtos = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), FindMachDto.class).stream().filter(item -> item != null && null != item.getCommTime()).collect(Collectors.toList());
                List<FindMachDto> alarmList = new ArrayList<>();
                List<FindMachDto> restoreList = new ArrayList<>();
                try {
                    for (FindMachDto dto : findMachDtos) {
                        long minutes = Duration.between(dto.getCommTime().toInstant(), now.toInstant()).toMinutes();
                        if (minutes >= dto.getAlarmTimes()) {
                            if (0 == dto.getAlarmState()) {
                                //则该设备为新生未推送通知的离线设备，添加到告警通知列表， 跳过本次循环
                                alarmList.add(dto);
                            }
                        } else {
                            if (0 != dto.getAlarmState()) {
                                //则该设备为已推送通知的在线设备，添加到恢复通知列表， 跳过本次循环
                                restoreList.add(dto);
                            }
                        }
                    }
                } catch (Exception e) {
//                    e.printStackTrace();
                    log.error("mjAlarmSend 异常1！【{}】", e);
                }

                //根据负责人合并设备为一条短信>> 修改为根据区域名称合并
                Map<String, List<FindMachDto>> alarmListMap = alarmList.stream().filter(item -> StringUtils.isNotBlank(item.getAreaName())).collect(Collectors.groupingBy(FindMachDto::getAreaName));
                if(alarmListMap!=null && alarmListMap.size()>0){
                    smsUser("2083495", "发生离线", 1, alarmListMap);
                }
                Map<String, List<FindMachDto>> restoreListMap = restoreList.stream().filter(item -> StringUtils.isNotBlank(item.getAreaName())).collect(Collectors.groupingBy(FindMachDto::getAreaName));
                if(restoreListMap!=null &&restoreListMap.size()>0){
                    smsUser("2083495", "成功连线", 0, restoreListMap);
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("mjAlarmSend异常2！【{}】【{}】", comId,e);
            return ResultUtil.error(2010);
        }
        return ResultUtil.success();
    }

    public static void main(String[] args) {
        Date date = new Date(2024, 03, 01, 12, 30);
        Date date2 = new Date(2024, 03, 01, 12, 35, 33);
        long minutes = Duration.between(date.toInstant(), date2.toInstant()).toMinutes();
        System.out.println(minutes);
    }

    private void smsUser(String TemplateId, String type, Integer alarmState, Map<String, List<FindMachDto>> listMap) {
        for (Map.Entry<String, List<FindMachDto>> entry : listMap.entrySet()) {
            try {
                List<FindMachDto> value = entry.getValue();
                Map<String, Object> map = new HashMap<>();
                FindMachDto findMachDto = value.get(0);
                //获取区域信息，用于匹配出片区id
                Result getAreaInfo = accessService.GetAreaInfo(findMachDto.getComId(),-1,findMachDto.getAreaId().intValue(),"");

                if (getAreaInfo.getCode() == 200) {
                    try {
                        if (getAreaInfo.getData() != null) {
                            List<EntityMjAreaInfo> entityMjAreaInfos  = JSON.parseArray(JSON.toJSONString(getAreaInfo.getData()), EntityMjAreaInfo.class);
                            for (EntityMjAreaInfo entityMjAreaInfo : entityMjAreaInfos) {
                                findMachDto.setRegionId(entityMjAreaInfo.getRegionId());
                                break;
                            }
                        }
                    } catch (Exception e) {

                    }
                }


                JSONObject jsonObject = new JSONObject();
                MapKey mapKey = new MapKey();
                jsonObject.put(mapKey.getKey_comId(),findMachDto.getComId());
                jsonObject.put(mapKey.getKey_regionId(),findMachDto.getRegionId());

                jsonObject.put(mapKey.getKey_status(),0);
                jsonObject.put(mapKey.getKey_page(),1);
                jsonObject.put(mapKey.getKey_size(),1000);
                Result result = humanClientService.getMngUserInfo(jsonObject);


                if (200 == result.getCode()) {

                    JSONObject retJsonObject=JSON.parseObject(JSON.toJSONString(result.getData()));
                    List<EntityMngUserInfo> entityMngUserInfos= JSON.parseArray(JSON.toJSONString(retJsonObject.get("list")), EntityMngUserInfo.class);
                    for (EntityMngUserInfo entityMngUserInfo : entityMngUserInfos) {
                        sendSms(findMachDto.getUserName(), TemplateId, type, entityMngUserInfo.getPhone(), String.valueOf(value.size()), value.stream().map(FindMachDto::getDeviceName).collect(Collectors.joining(",")));
                    }
                }
                UpdateMachByAlarmRequest updateMachByAlarmRequest = new UpdateMachByAlarmRequest();
                updateMachByAlarmRequest.setAlarmState(alarmState);
                updateMachByAlarmRequest.setComId(findMachDto.getComId());
                updateMachByAlarmRequest.setDeviceNos(value.stream().map(FindMachDto::getDeviceNo).collect(Collectors.toList()));
                accessService.updateMachByAlarm(updateMachByAlarmRequest);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    private void sendSms(String userName, String TemplateId, String type, String phone, String total, String deviceNames) {
        try {
            if (StringUtils.isNotBlank(TemplateId) && StringUtils.isNotBlank(phone)) {
                SmsRequest request = new SmsRequest();

                request.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
                request.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
                request.setSignName("鑫澳康科技");
                request.setSdkAppId("1400314290");

                request.setTemplateId(TemplateId);


                request.setPhone(phone);

                request.getParams().add(total);
                request.getParams().add(type);
                request.getParams().add(limitStringWithEllipsis(deviceNames, 15));
                try {
                    log.info("发送门禁告警短信 【{}】", request);
                    Result result = mqSimpleFeign.FySms(request);
                    log.info("发送门禁告警短信结果 【{}】", result);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("发送门禁告警短信异常 【{}】", e);
                }
            } else {
                log.info("发送门禁告警短信发送失败，phone为空 【{}】", userName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("门禁告警短信发生失败：【{}】", e);

        }

    }

    public static String limitStringWithEllipsis(String input, int maxLength) {
        if (input == null || input.length() <= maxLength) {
            // 如果输入为空或已小于等于最大长度，则直接返回输入字符串
            return input;
        } else {
            // 否则截取前maxLength-3个字符，并添加省略号
            return input.substring(0, maxLength - 3) + "...";
        }
    }

}
